/**
 * Copyright 2021 nicos AG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Simon Petrac <spetrac@nicos-ag.com>
 * @contributor Jörg Langkau <jlangkau@nicos-ag.com>
 * @license Apache-2.0
 */

const
    tcs_md_renderer       = exports,
    md_renderer           = require('./renderer.md.js'),
    util                  = require('./util.js'),
    FIR_keywords_literals = {
        attribute:   {'en': 'Attribute'},
        value:       {'en': 'Value'},
        step:        {'en': 'Step'},
        description: {'en': 'Description'},
        previous:    {'en': 'Previous'},
        next:        {'en': 'Next'}
    },
    FIR_label_literals    = {
        coveredTDS:       {'en': 'Covered Test Design Specification'},
        testRole:         {'en': 'Test Role'},
        testConfig:       {'en': 'Test Config'},
        seeAlso:          {'en': 'See Also'},
        initialCondition: {'en': 'Initial Condition'},
        trigger:          {'en': 'Trigger'},
        expectedBehavior: {'en': 'Expected Behavior'},
        finalCondition:   {'en': 'Final Condition'}
    };

tcs_md_renderer['FIR_STATIC_footer'] = function (param, config) {
    return md_renderer['FIR_STATIC_footer'](param, config);
}; // FIR_STATIC_footer

tcs_md_renderer['FIR_TOP_CHAPTER'] = function (param, config) {
    const
        {data, graph}             = param,
        {language, specification} = config,
        componentTCS              = graph.get(specification);
    return util.getLangStringFromLiterals(componentTCS['rdfs:label'], language);
}; // FIR_TOP_CHAPTER

tcs_md_renderer['FIR_TOP_description'] = function (param, config) {
    const
        {data, graph}             = param,
        {language, specification} = config,
        componentTCS              = graph.get(specification),
        description               = util.getLangStringFromLiterals(componentTCS['dct:description'], language);
    return util.textToMarkdown(description.trim());
}; // FIR_TOP_description

tcs_md_renderer['FIR_TOP_comments'] = function (param, config) {
    const
        {data, graph}             = param,
        {language, specification} = config,
        componentTCS              = graph.get(specification),
        applicableComments        = util.toArray(componentTCS['rdfs:comment'])
            .filter(literal => literal['@value'] && (!literal['@language'] || literal['@language'] === language));
    return applicableComments
        .map(literal => literal['@value'].replace(/^/mg, '> '))
        .join('\n\n');
}; // FIR_TOP_comments

tcs_md_renderer['FIR_TestCase_overview'] = function (param, config) {
    const
        {data, graph}             = param,
        {language, specification} = config,
        componentTCS              = graph.get(specification),
        // coveredTDS_colName        = util.getLangStringFromLiterals(graph.get('ids3cm:coveredTDS'), language) || 'coveredTDS',
        coveredTDS_colName        = FIR_label_literals.coveredTDS[language] || 'coveredTDS',
        // testRole_colName          = util.getLangStringFromLiterals(graph.get('ids3cm:testRole'), language) || 'testRole',
        testRole_colName          = FIR_label_literals.testRole[language] || 'testRole',
        // testConfig_colName        = util.getLangStringFromLiterals(graph.get('ids3cm:testConfig'), language) || 'testConfig',
        testConfig_colName        = FIR_label_literals.testConfig[language] || 'testConfig',
        // seeAlso_colName           = util.getLangStringFromLiterals(graph.get('rdfs:seeAlso'), language) || 'seeAlso',
        seeAlso_colName           = FIR_label_literals.seeAlso[language] || 'seeAlso',
        coveredTDS_arr            = util.toArray(componentTCS['ids3cm:coveredTDS']).sort(util.compareNodes),
        testRole                  = componentTCS['ids3cm:testRole'],
        testConfig                = componentTCS['ids3cm:testConfig'],
        seeAlso_arr               = util.toArray(componentTCS['rdfs:seeAlso']).sort(util.compareNodes);

    let testCaseOverview = `| ${FIR_keywords_literals.attribute[language]} | ${FIR_keywords_literals.value[language]} |`;
    testCaseOverview += '\n|:---|:---|';

    if (coveredTDS_arr.length > 0) {
        for (let i = 0; i < coveredTDS_arr.length; i++) {
            const
                coveredTDS_id       = coveredTDS_arr[i]['@id'].replace('ids3c-co:', ''),
                coveredTDS_label    = util.getLangStringFromLiterals(coveredTDS_arr[i]['rdfs:label'], language),
                coveredTDS_colValue = `[${coveredTDS_label || coveredTDS_id}](../../design/specs/${coveredTDS_id}.md)`;
            testCaseOverview += `\n| ${i === 0 ? coveredTDS_colName : ' '} | ${coveredTDS_colValue} |`;
        }
    } else {
        testCaseOverview += `\n| ${coveredTDS_colName} | - |`;
    }

    if (testRole && testRole['@id']) {
        const
            testRole_id       = testRole['@id'].replace('ids3cm:', '').replace('ids3c-co:', ''),
            testRole_label    = util.getLangStringFromLiterals(testRole['rdfs:label'], language),
            testRole_colValue = testRole_label || (testRole_id.startsWith('_:') ? '_FIXME_' : testRole_id);
        testCaseOverview += `\n| ${testRole_colName} | ${testRole_colValue} |`;
    } else {
        testCaseOverview += `\n| ${testRole_colName} | - |`;
    }

    if (testConfig && testConfig['@id']) {
        const
            testConfig_id          = testConfig['@id'].replace('ids3cm:', '').replace('ids3c-co:', ''),
            testConfig_label       = util.getLangStringFromLiterals(testConfig['rdfs:label'], language),
            testConfig_description = util.textToMarkdown(util.getLangStringFromLiterals(testConfig['dct:description'], language)),
            testConfig_colValue    = testConfig_description || testConfig_label || (testConfig_id.startsWith('_:') ? '_FIXME_' : testConfig_id);
        testCaseOverview += `\n| ${testConfig_colName} | ${testConfig_colValue} |`;
    } else {
        testCaseOverview += `\n| ${testConfig_colName} | - |`;
    }

    if (seeAlso_arr.length > 0) {
        for (let i = 0; i < seeAlso_arr.length; i++) {
            const
                seeAlso_id       = seeAlso_arr[i]['@id'],
                seeAlso_colValue = `[${seeAlso_id}](${seeAlso_id})`;
            testCaseOverview += `\n| ${i === 0 ? seeAlso_colName : ' '} | ${seeAlso_colValue} |`;
        }
    } else {
        testCaseOverview += `\n| ${seeAlso_colName} | - |`;
    }

    return testCaseOverview;
}; // FIR_TestCase_overview

tcs_md_renderer['FIR_TestCase_procedure'] = function (param, config) {
    const
        {data, graph}             = param,
        {language, specification} = config,
        componentTCS              = graph.get(specification),
        // initialCondition_colName  = util.getLangStringFromLiterals(graph.get('ids3cm:initialCondition'), language) || 'initialCondition',
        initialCondition_colName  = FIR_label_literals.initialCondition[language] || 'initialCondition',
        // trigger_colName           = util.getLangStringFromLiterals(graph.get('ids3cm:trigger'), language) || 'trigger',
        trigger_colName           = FIR_label_literals.trigger[language] || 'trigger',
        // expectedBehavior_colName  = util.getLangStringFromLiterals(graph.get('ids3cm:expectedBehavior'), language) || 'expectedBehavior',
        expectedBehavior_colName  = FIR_label_literals.expectedBehavior[language] || 'expectedBehavior',
        // finalCondition_colName    = util.getLangStringFromLiterals(graph.get('ids3cm:finalCondition'), language) || 'finalCondition',
        finalCondition_colName    = FIR_label_literals.finalCondition[language] || 'finalCondition',
        initialCondition          = componentTCS['ids3cm:initialCondition'],
        trigger                   = componentTCS['ids3cm:trigger'],
        expectedBehavior          = componentTCS['ids3cm:expectedBehavior'],
        finalCondition            = componentTCS['ids3cm:finalCondition'];

    let testCaseProcedure = `| ${FIR_keywords_literals.step[language]} | ${FIR_keywords_literals.description[language]} |`;
    testCaseProcedure += '\n|:---|:---|';

    if (initialCondition && initialCondition['@id']) {
        const
            initialCondition_id          = initialCondition['@id'].replace('ids3c-co:', ''),
            initialCondition_label       = util.getLangStringFromLiterals(initialCondition['rdfs:label'], language),
            initialCondition_description = util.textToMarkdown(util.getLangStringFromLiterals(initialCondition['dct:description'], language)),
            initialCondition_colValue    = initialCondition_description || initialCondition_label || (initialCondition_id.startsWith('_:') ? '_FIXME_' : initialCondition_id);
        testCaseProcedure += `\n| ${initialCondition_colName} | ${initialCondition_colValue} |`;
        if (initialCondition['ids3cm:testCaseSpecification']) {
            const tcsRef_arr = util.toArray(initialCondition['ids3cm:testCaseSpecification'])
                .sort(util.compareNodes)
                .map((tcsRef) => {
                    const
                        tcsRef_id    = tcsRef['@id'].replace('ids3c-co:', ''),
                        tcsRef_label = util.getLangStringFromLiterals(tcsRef['rdfs:label'], language);
                    return `[${tcsRef_label || tcsRef_id}](./${tcsRef_id}.md)`
                });
            testCaseProcedure += `\n|   | ${FIR_keywords_literals.previous[language]} TCS: ${tcsRef_arr.join(', ')} |`;
        }
    } else {
        testCaseProcedure += `\n| ${initialCondition_colName} | - |`;
    }

    if (trigger) {
        const trigger_text = util.textToMarkdown(util.getLangStringFromLiterals(trigger, language));
        testCaseProcedure += `\n| ${trigger_colName} | ${trigger_text} |`;
    } else {
        testCaseProcedure += `\n| ${trigger_colName} | - |`;
    }

    if (expectedBehavior) {
        const expectedBehavior_text = util.textToMarkdown(util.getLangStringFromLiterals(expectedBehavior, language));
        testCaseProcedure += `\n| ${expectedBehavior_colName} | ${expectedBehavior_text} |`;
    } else {
        testCaseProcedure += `\n| ${expectedBehavior_colName} | - |`;
    }

    if (finalCondition && finalCondition['@id']) {
        const
            finalCondition_id          = finalCondition['@id'].replace('ids3c-co:', ''),
            finalCondition_label       = util.getLangStringFromLiterals(finalCondition['rdfs:label'], language),
            finalCondition_description = util.textToMarkdown(util.getLangStringFromLiterals(finalCondition['dct:description'], language)),
            finalCondition_colValue    = finalCondition_description || finalCondition_label || (finalCondition_id.startsWith('_:') ? '_FIXME_' : finalCondition_id);
        testCaseProcedure += `\n| ${finalCondition_colName} | ${finalCondition_colValue} |`;
        if (finalCondition['ids3cm:testCaseSpecification']) {
            const tcsRef_arr = util.toArray(finalCondition['ids3cm:testCaseSpecification'])
                .sort(util.compareNodes)
                .map((tcsRef) => {
                    const
                        tcsRef_id    = tcsRef['@id'].replace('ids3c-co:', ''),
                        tcsRef_label = util.getLangStringFromLiterals(tcsRef['rdfs:label'], language);
                    return `[${tcsRef_label || tcsRef_id}](./${tcsRef_id}.md)`
                });
            testCaseProcedure += `\n|   | ${FIR_keywords_literals.next[language]} TCS: ${tcsRef_arr.join(', ')} |`;
        }
    } else {
        testCaseProcedure += `\n| ${finalCondition_colName} | - |`;
    }

    return testCaseProcedure;
}; // FIR_TestCase_procedure
